package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.place;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.data.ValidateTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceClerk;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.services.PlaceClerkService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.ELoginUserRoleType;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceClerkDelRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceClerkListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceClerkListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceClerkSaveRequest;

public class PlaceClerkController {

	@Route(value = "/agent/api/v1/place/clerk/list.data")
    public PlaceClerkListResponse userList(HttpServletRequest request){
		PlaceClerkListResponse apiResp = new PlaceClerkListResponse(ClientAPICodeConstants.NULL_DATA,"暂无数据");
		PlaceClerkListRequest apiReq = WebUtils.getJsonRequest(request,PlaceClerkListRequest.class);
        if(apiReq != null && apiReq.getBody().getPlaceId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && (ELoginUserRoleType.Agent.index().equals(loginUser.getRoleType()) 
            		|| ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType()))) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
                if (physicalStore != null) {
                	boolean flag = false;
                	if(ELoginUserRoleType.Agent.index().equals(loginUser.getRoleType())) {
                		if(physicalStore.getUserId().equals(loginUser.getId())) {
                			flag = true;
                		}
                	}else if(ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType())) {
                		PlaceProfitUser profitUser = PlaceProfitUserService.self().getByKeys(physicalStore.getId(), loginUser.getId());
                		if(profitUser != null && ERoleType.Merchant.index().equals(profitUser.getRoleType())) {
                			flag = true;
                		}
                	}
                	
                	if(flag) {
                		List<PlaceClerk> placeClerkList = PlaceClerkService.self().findJoinByPlaceId(physicalStore.getId());
                		if(placeClerkList != null && placeClerkList.size() > 0){
                			 //网点是当前用户创建的
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                            apiResp.getBody().setItems(new ArrayList<>());
                            
                            for(PlaceClerk placeClerk : placeClerkList) {
                            	PlaceClerkListResponse.Item item = new PlaceClerkListResponse.Item();
                            	item.setUserId(placeClerk.getUserId());
                            	item.setUserName(placeClerk.getUser().getName());
                            	item.setUserPhone(placeClerk.getUser().getPhone());
                            	item.setCreateDate(placeClerk.getCreateDate());
                            	apiResp.getBody().getItems().add(item);
                            }
                		}
                	}else{
                		apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
                	}
                } else {
                    apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
                }
            } else {
                apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/place/clerk/save.do")
    public DefaultAPIResponse doSave(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "保存店员失败");
        PlaceClerkSaveRequest apiReq = WebUtils.getJsonRequest(request, PlaceClerkSaveRequest.class);
        if (apiReq != null && apiReq.getBody().getPlaceId() != null && StringTools.isNotBlank(apiReq.getBody().getPhone())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null&& (ELoginUserRoleType.Agent.index().equals(loginUser.getRoleType()) || ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType()))) {
            	if (!ValidateTools.isPhone(apiReq.getBody().getPhone())) {
                    apiResp.setMsg("手机号不正确，请检查");
                    return apiResp;
                }
            	
            	PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
                if (physicalStore != null) {
                	boolean flag = false;
                	Long merchantUserId = loginUser.getId();
                	if(ELoginUserRoleType.Agent.index().equals(loginUser.getRoleType())) {
                		if(physicalStore.getUserId().equals(loginUser.getId())) {
                			List<PlaceProfitUser> profitUserList = PlaceProfitUserService.self().findByPlaceId(physicalStore.getId());
                			if(profitUserList != null && profitUserList.size() > 0) {
                				for(PlaceProfitUser profitUser : profitUserList) {
                					if(ERoleType.Merchant.index().equals(profitUser.getRoleType())) {
                						merchantUserId = profitUser.getUserId();
                						break;
                					}
                				}
                			}
                			if(merchantUserId != null) {
                				flag = true;
                			}else {
                				apiResp.setMsg("网点未设置商户，请先设置商户再设置店员");
                                return apiResp;
                			}
                		}
                	}else if(ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType())) {
                		PlaceProfitUser profitUser = PlaceProfitUserService.self().getByKeys(physicalStore.getId(), loginUser.getId());
                		if(profitUser != null && ERoleType.Merchant.index().equals(profitUser.getRoleType())) {
                			merchantUserId = loginUser.getParentId();
                			flag = true;
                		}
                	}
                	
                	if(flag) {
                		User user = UserService.self().getByPhone(apiReq.getBody().getPhone());
                        if (user == null) {
                            if (StringTools.isBlank(apiReq.getBody().getName())) {
                                apiResp.setMsg("用户不存在，请填写用户姓名");
                                return apiResp;
                            }
                            user = new User();
                            user.setName(apiReq.getBody().getName());
                            user.setPhone(apiReq.getBody().getPhone());
                            user.setReferrerId(loginUser.getId());
                            user.setReferrerName(loginUser.getFullName());
                        }
                        
                        PlaceClerk placeClerk = new PlaceClerk();
                        placeClerk.setPlaceId(physicalStore.getId());
                        placeClerk.setAgentUserId(physicalStore.getUserId());
                        placeClerk.setMerchantUserId(merchantUserId);
                        
                        try {
							if(PlaceClerkService.self().add(placeClerk,user,apiReq.getBody().getNote())) {
								apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
							}
						} catch (LogicException e) {
							apiResp.setMsg(e.getMessage());
						}
                	}else {
                		apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
                	}
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/place/clerk/del.do")
    public DefaultAPIResponse doDelUser(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "删除店员失败");
        PlaceClerkDelRequest apiReq = WebUtils.getJsonRequest(request, PlaceClerkDelRequest.class);
        if (apiReq != null && apiReq.getBody().getPlaceId() != null && apiReq.getBody().getUserId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
            	PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
                if (physicalStore != null) {
                	boolean flag = false;
                	Long merchantUserId = null;
                	if(ELoginUserRoleType.Agent.index().equals(loginUser.getRoleType())) {
                		if(physicalStore.getUserId().equals(loginUser.getId())) {
                			List<PlaceProfitUser> profitUserList = PlaceProfitUserService.self().findByPlaceId(physicalStore.getId());
                			if(profitUserList != null && profitUserList.size() > 0) {
                				for(PlaceProfitUser profitUser : profitUserList) {
                					if(ERoleType.Merchant.index().equals(profitUser.getRoleType())) {
                						merchantUserId = profitUser.getUserId();
                						break;
                					}
                				}
                			}
                			if(merchantUserId != null) {
                				flag = true;
                			}else {
                				apiResp.setMsg("网点未设置商户，请先设置商户再设置店员");
                                return apiResp;
                			}
                		}
                	}else if(ELoginUserRoleType.Dealer.index().equals(loginUser.getRoleType())) {
                		PlaceProfitUser profitUser = PlaceProfitUserService.self().getByKeys(physicalStore.getId(), loginUser.getId());
                		if(profitUser != null && ERoleType.Merchant.index().equals(profitUser.getRoleType())) {
                			merchantUserId = loginUser.getParentId();
                			flag = true;
                		}
                	}
                	
                	if(flag) {
		                try {
		                    if (PlaceClerkService.self().deleteBykeys(apiReq.getBody().getPlaceId(), apiReq.getBody().getUserId())) {
		                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
		                    }
		                } catch (LogicException e) {
		                    apiResp.setMsg(e.getMessage());
		                }
                	}
                }
            }
        }
        return apiResp;
    }

}
